// axiosRequestConfig 是给 axios 扩展个性化配置
// axiosError
import axios, { AxiosRequestConfig, AxiosError } from "axios";
// import loading from './loading'
import {
  ElMessage,
  ElLoading,
  ILoadingInstance,
} from "element-plus";

let baseURL = "/admin";

// 创建axios实例
const service = axios.create({
  baseURL,
  withCredentials: true,
  timeout: 10000, // 请求超时时间
});

let loading: ILoadingInstance; // 加载动画
const checkRequestAuth = (url: string) => {
  return url.includes('usr/getCaptcha') || url == '/rest/usr/login'
}
/**
 * @description 拦截器，用于权限的管理
 */
// 请求拦截器
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    const Authorization =
      sessionStorage.getItem("token") &&
      `Bearer ${sessionStorage.getItem("token")}`;
    const userId =
      sessionStorage.getItem("userId") && `${sessionStorage.getItem("userId")}`;
    const challenge =
      sessionStorage.getItem("challenge") &&
      `${sessionStorage.getItem("challenge")}`;
    // const token = sessionStorage.getItem('token')
    if (!checkRequestAuth(config.url) && (!Authorization || !userId || !challenge)) {
      return (location.href = '/');
    }
    config.headers = {
      Authorization,
      userId,
      challenge,
      //   xip: sessionStorage.getItem("Ip"),
      "Content-Type": "application/json;charset=UTF-8",
    };
    loading = ElLoading.service({
      text: "操作中...",
      spinner: "el-icon-loading ElementLoading",
      background: "rgba(0, 0, 0, 0.2)",
    });
    // }
    return config;
  },
  (err: AxiosError) => {
    return Promise.reject(err);
  }
);
// resopnse拦截器
service.interceptors.response.use(
  (response) => {
    if (loading) {
      loading.close()
    }
    // let { statusCode } = response.data
    // // token验证失败，重新登录
    // if(statusCode === 20020) {
    //   removetoken()
    // }

    // if(statusCode === 20021) {
    //   Message.error('网关失败')
    // }

    if (response) {
      return response;
    }
  },
  (err: AxiosError) => {
    if (loading) {
      loading.close()
    }
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = "错误请求";
          break;
        case 401:
          err.message = "未授权，请重新登录！";
          break;
        case 403:
          err.message = "拒绝访问";
          break;
        case 404:
          err.message = "请求错误,未找到该资源！";
          break;
        case 405:
          err.message = "请求方法未允许";
          break;
        case 408:
          err.message = "请求超时";
          break;
        case 500:
          err.message = "服务器端出错";
          break;
        case 501:
          err.message = "网络未实现";
          break;
        case 502:
          err.message = "网络错误";
          break;
        case 503:
          err.message = "服务不可用";
          break;
        case 504:
          err.message = "网络超时";
          break;
        case 505:
          err.message = "http版本不支持该请求";
          break;
        default:
          err.message = `连接错误${err.response.status}`;
      }
    } else {
      if (err.message.includes('timeout')) {
        ElMessage({
          message: '请求超时',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        console.log(err.message)
      }
    }

    if (err && err.response) {
      ElMessage.error(err.message);
    }
    return Promise.reject(err);
  }
);

export default service